package com.peng.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.peng.pojo.Admin;
import com.peng.pojo.LoginForm;
import com.peng.pojo.Student;
import com.peng.pojo.Teacher;
import com.peng.service.AdminService;
import com.peng.service.StudentService;
import com.peng.service.TeacherService;
import com.peng.utils.*;
import io.jsonwebtoken.JwtBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/sms/system")
public class SystemController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @PostMapping("/updatePwd/{password}/{newpassword}")
    public Result updatePwd(@RequestHeader("token")String token, @PathVariable("password")String password,@PathVariable("newpassword") String newpassword){
        Long userId = JwtHelper.getUserId(token);
        Integer userType = JwtHelper.getUserType(token);
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration){
            return Result.fail().message("登录已过期");
        }
        switch (userType){
            case 1:
                LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
                adminLambdaQueryWrapper.eq(Admin::getId,userId);
                adminLambdaQueryWrapper.eq(Admin::getPassword,MD5.encrypt(password));
                Admin one = adminService.getOne(adminLambdaQueryWrapper);
                if (one!=null){
                    one.setPassword(MD5.encrypt(newpassword));
                    adminService.saveOrUpdate(one);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
            case 2:
                LambdaQueryWrapper<Student> adminLambdaQueryWrapper1 = new LambdaQueryWrapper<>();
                adminLambdaQueryWrapper1.eq(Student::getId,userId);
                adminLambdaQueryWrapper1.eq(Student::getPassword, MD5.encrypt(password));
                Student one1 = studentService.getOne(adminLambdaQueryWrapper1);
                if (one1!=null){
                    one1.setPassword(MD5.encrypt(newpassword));
                    studentService.saveOrUpdate(one1);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
            case 3:
                LambdaQueryWrapper<Teacher> adminLambdaQueryWrapper2 = new LambdaQueryWrapper<>();
                adminLambdaQueryWrapper2.eq(Teacher::getId,userId);
                adminLambdaQueryWrapper2.eq(Teacher::getPassword, MD5.encrypt(password));
                Teacher one2 = teacherService.getOne(adminLambdaQueryWrapper2);
                if (one2!=null){
                    one2.setPassword(MD5.encrypt(newpassword));
                    teacherService.saveOrUpdate(one2);
                }else {
                    return Result.fail().message("原密码有误");
                }
                break;
        }
        return Result.ok();
    }

    @PostMapping("/headerImgUpload")
    public Result headerImgUpload(
            @RequestPart("multipartFile")MultipartFile multipartFile,
            HttpServletRequest request){
        String originalFilename = multipartFile.getOriginalFilename();
        String s = UUID.randomUUID().toString().replace("-", "").toLowerCase().substring(10);
        String substring = originalFilename.substring(originalFilename.indexOf("."));
        String str=s+substring;
        String path =("F:/学习笔记/myproject/zhxy_db/src/main/resources/public/upload/")+str;
        try {
            multipartFile.transferTo(new File(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
        String pathFile="upload/".concat(str);
        return Result.ok(pathFile);
    }

    @GetMapping("/getInfo")
    public Result getInfo(@RequestHeader String token){
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration){
            return Result.build(null, ResultCodeEnum.TOKEN_ERROR);
        }
        Long userId = JwtHelper.getUserId(token);
        String userName = JwtHelper.getUserName(token);
        Integer userType = JwtHelper.getUserType(token);
        Map<String, Object> map = new LinkedHashMap<>();
        switch (userType){
            case 1:
                Admin admin = adminService.getById(userId);
                map.put("userType",1);
                map.put("user",admin);
                break;
            case 2:
                Student student = studentService.getById(userId);
                map.put("userType",2);
                map.put("user",student);
                break;
            case 3:
                Teacher teacher = teacherService.getById(userId);
                map.put("userType",3);
                map.put("user",teacher);
                break;
        }
        return Result.ok(map);
    }

    @PostMapping("/login")
    public Result login(@RequestBody LoginForm loginForm,HttpServletRequest request){
        HttpSession session = request.getSession();
        String tokenverifiCode = String.valueOf(session.getAttribute("verifiCode"));
        String verifiCode = loginForm.getVerifiCode();
        if (tokenverifiCode.equals("")|| tokenverifiCode==null){
            return Result.fail().message("验证码过期，请刷新重试");
        }
        if (!tokenverifiCode.equalsIgnoreCase(verifiCode)){
            return Result.fail().message("验证码有误，请刷新重试");
        }
        session.removeAttribute("verifiCode");

        Map<String, Object> map = new LinkedHashMap<>();
        switch (loginForm.getUserType()){
            case 1:
                Admin admin= adminService.login(loginForm);
                try {
                    if (admin!=null){
                        String token= JwtHelper.createToken(admin.getId().longValue(),1);
                        map.put("token",token);
                    }else {
                        throw  new RuntimeException("用户名或者密码错误");
                    }
                    return Result.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }

            case 2:
                Student student= studentService.login(loginForm);
                try {
                    if (student!=null){
                        String token= JwtHelper.createToken(student.getId().longValue(),2);
                        map.put("token",token);
                    }else {
                        throw  new RuntimeException("用户名或者密码错误");
                    }
                    return Result.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
            case 3:
                Teacher teacher= teacherService.login(loginForm);
                try {
                    if (teacher!=null){
                        String token= JwtHelper.createToken(teacher.getId().longValue(),3);
                        map.put("token",token);
                    }else {
                        throw  new RuntimeException("用户名或者密码错误");
                    }
                    return Result.ok(map);
                } catch (Exception e) {
                    e.printStackTrace();
                    return Result.fail().message(e.getMessage());
                }
        }
        return Result.fail().message("没有该用户");
    }


    @GetMapping("/getVerifiCodeImage")
    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
        String verifiCode = String.valueOf(CreateVerifiCodeImage.getVerifiCode());
        HttpSession session = request.getSession();
        session.setAttribute("verifiCode",verifiCode);
        try {
            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
